import { ref, computed, onMounted, unref, onUnmounted } from "vue";
import { v4 as uuid } from "uuid";
import { getTasksListLocalstory, saveTasksListLocalstory } from "../utils";

// 最大数量
const maxTaskLen = 20;

// 任务钩子
export function useTasks() {
  const tasks = ref([]);
  const draggableDisabled = ref(false); // 是否禁用拖拽
  const isDrag = ref(false);
  // 当天日期
  const nowTime = computed(() => {
    const date = new Date();
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, 0);
    const day = date.getDate().toString().padStart(2, 0);
    return `${year}-${month}-${day}`;
  });
  // 设置任务
  const setTasks = (newTasks) => {
    tasks.value = newTasks;
  };
  // 添加任务
  const handleAddTask = () => {
    isDrag.value = true;
    if (unref(tasks).length > maxTaskLen) {
      alert(`最多创建 ${maxTaskLen} 个任务哦～`);
      return;
    }
    draggableDisabled.value = true;
    setTasks([
      {
        id: uuid(),
        label: "",
        isEdit: true,
        checked: false,
      },
      ...unref(tasks),
    ]);
  };
  // 移除任务
  const handleRemoveTask = (task) => {
    isDrag.value = true;
    const newTasks = unref(tasks).filter((item) => item.id !== task.id);
    setTasks(newTasks);
    saveTasksListLocalstory(newTasks); // 更新插件数据
  };
  // 失去焦点
  const handleInputBlur = (task) => {
    if (task.label.trim() !== "") {
      task.isEdit = false;
      saveTasksListLocalstory([...unref(tasks)]);
    } else {
      handleRemoveTask(task); // 执行删除操作
    }
    draggableDisabled.value = false;
  };
  // 编辑任务
  const handleEditTask = (task) => {
    if (!task.isEdit) {
      task.isEdit = true;
    }
  };
  // 拖拽开始
  const onStart = () => {
    console.log("开始");
    isDrag.value = true;
  };
  // 拖拽结束
  const onEnd = () => {
    console.log("结束");
    isDrag.value = false;
    saveTasksListLocalstory([...unref(tasks)]);
  };
  // 多选框事件
  const handleCheckboxChange = (task) => {
    const temp = unref(tasks).filter((el) => el.id !== task.id);
    if (task.checked) {
      isDrag.value = true;
      temp.push(task);
    } else {
      temp.unshift(task);
    }
    setTasks(temp);
    saveTasksListLocalstory(temp);
  };
  onMounted(() => {
    getTasksListLocalstory(setTasks); // 初始化任务列表
  });
  onUnmounted(() => {
    saveTasksListLocalstory([...unref(tasks)]); // 组件卸载设置数据
  });
  return {
    tasks,
    isDrag,
    draggableDisabled,
    nowTime,
    setTasks,
    handleAddTask,
    onStart,
    onEnd,
    handleEditTask,
    handleInputBlur,
    handleRemoveTask,
    handleCheckboxChange,
  };
}
